package com.zjhcsoft.auth.gateway.filter;

import io.netty.handler.ipfilter.IpFilterRuleType;
import io.netty.handler.ipfilter.IpSubnetFilterRule;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

/**
 * ESB过来的报文解析
 */
@Component
public class EsbXmlSTringDecode extends AbstractGatewayFilterFactory<EsbXmlSTringDecode.Config> {

    private static final Log log = LogFactory.getLog(EsbXmlSTringDecode.class);

    public EsbXmlSTringDecode() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("forbidIp");
    }

    public static String getIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");

        return ip;
    }

    private List<IpSubnetFilterRule> convert(List<String> values) {
        List<IpSubnetFilterRule> sources = new ArrayList<>();
        return sources;
    }


    @Override
    public GatewayFilter apply(Config config) {
        List<IpSubnetFilterRule> sources = convert(config.sources);

        return (exchange, chain) -> {

            String ip = getIpAddress(exchange.getRequest());

            log.warn("Remote addresses didn't match " + ip );


            InetSocketAddress remoteAddress=   new InetSocketAddress(ip, 2345);
            for (IpSubnetFilterRule source : sources) {
                if (source.matches(remoteAddress)) {
                    return chain.filter(exchange);
                }
            }
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);




            return exchange.getResponse().setComplete();

        };
    }

    static public class Config {

        private List<String> sources = new ArrayList<>();

        public List<String> getSources() {
            return sources;
        }

        public void setSources(List<String> sources) {
            this.sources = sources;
        }
    }

}
